const express = require('express')
const bodyParser = require('body-parser')
const webpack = require('webpack')
const webpackDevMiddleware = require('webpack-dev-middleware')
const webpackHotMiddleware = require('webpack-hot-middleware')
const WebpackConfig = require('./webpack.config')
const router = express.Router()
const cookies = require('cookie-parser')
const atob = require('atob')
const { STATUS_CODES } = require('http')

const app = express()
const compiler = webpack(WebpackConfig)

app.use(
  webpackDevMiddleware(compiler, {
    publicPath: '/__build__/',
    stats: {
      colors: true,
      chunks: false,
    },
  })
)

app.use(webpackHotMiddleware(compiler))

app.use(
  express.static(__dirname, {
    setHeaders(res) {
      res.cookie('XSRF-TOKEN-D', 'abc123')
    },
  })
)

app.use(bodyParser.json())
app.use(bodyParser.urlencoded({ extended: true }))
app.use(cookies())

registerSimpleRouter()
registerBaseRouter()
registerErrorRouter()
registerExtendRouter()
registerInterceptorRouter()
registerConfigRouter()
registerCancelRouter()
registerMoreRouter()

app.use(router)

require('./server2')

const port = process.env.PORT || 8081
module.exports = app.listen(port, () => {
  console.log(`Server listening on http://localhost:${port}, Ctrl+C to stop`)
})

function registerSimpleRouter() {
  router.get('/simple/get', (req, res) => {
    res.json({
      msg: `hello world`,
    })
  })
}

function registerBaseRouter() {
  router.get('/base/get', (req, res) => {
    res.json(req.query)
  })

  router.post('/base/post', (req, res) => {
    res.json(req.body)
  })

  router.post('/base/buffer', (req, res) => {
    let msg = []
    req.on('data', (chunk) => {
      if (chunk) {
        msg.push(chunk)
      }
    })
    req.on('end', () => {
      let buf = Buffer.concat(msg)
      res.json(buf.toJSON())
    })
  })
}

function registerErrorRouter() {
  router.get('/error/get', function (req, res) {
    if (Math.random() > 0.5) {
      res.json({
        msg: `hello world`,
      })
    } else {
      res.status(500)
      res.end()
    }
  })

  router.get('/error/timeout', function (req, res) {
    setTimeout(() => {
      res.json({
        msg: `hello world`,
      })
    }, 3000)
  })
}

function registerExtendRouter() {
  router.get('/extend/get', (req, res) => {
    res.send('get')
  })

  router.options('/extend/options', (req, res) => {
    res.send('options')
  })

  router.delete('/extend/delete', (req, res) => {
    res.send('delete')
  })

  router.head('/extend/head', (req, res) => {
    res.send('head')
  })

  router.post('/extend/post', (req, res) => {
    res.send(req.body)
  })

  router.put('/extend/put', (req, res) => {
    res.send(req.body)
  })

  router.patch('/extend/patch', (req, res) => {
    res.send(req.body)
  })

  router.get('/extend/user', (req, res) => {
    res.send({
      code: 10001,
      message: 'success',
      result: {
        userId: 100010,
        name: 'hello',
        age: 18,
      },
    })
  })
}

function registerInterceptorRouter() {
  router.get('/interceptor/get', (req, res) => {
    res.send('hello')
  })
}

function registerConfigRouter() {
  router.post('/config/post', (req, res) => {
    res.send(req.body)
  })
}

function registerCancelRouter() {
  router.get('/cancel/get', (req, res) => {
    setTimeout(() => {
      res.json('hello')
    }, 1000)
  })

  router.post('/cancel/post', (req, res) => {
    setTimeout(() => {
      res.json(req.body)
    }, 1000)
  })
}

function registerMoreRouter() {
  router.get('/more/get', (req, res) => {
    res.json(req.cookies)
  })
  router.post('/more/login', (req, res) => {
    const { authorization: auth } = req.headers
    const [types, info] = auth.split(new RegExp('\\s'))
    const [username, password] = atob(info).split(':')
    console.log(types, username, password)
    if (types === 'Basic' && username === 'luoob' && password === '123456') {
      res.json({
        message: '登录成功',
      })
    } else {
      res.status(401)
      res.end(STATUS_CODES[401])
    }
  })

  router.get('/more/A', (req, res) => {
    res.send('A')
  })

  router.get('/more/B', (req, res) => {
    res.send('B')
  })
}
